package com.answer.petsale.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.answer.petsale.annotation.AuthCheck;
import com.answer.petsale.common.BaseResponse;
import com.answer.petsale.common.ErrorCode;
import com.answer.petsale.common.ResultUtils;
import com.answer.petsale.exception.BusinessException;
import com.answer.petsale.model.dto.order.OrderCreateRequest;
import com.answer.petsale.model.dto.order.OrderQueryRequest;
// START: 新增导入
import com.answer.petsale.model.dto.order.OrderRejectRequest;
// END: 新增导入
import com.answer.petsale.model.entity.Order;
import com.answer.petsale.model.entity.User;
import com.answer.petsale.model.vo.OrderVO;
import com.answer.petsale.service.OrderService;
import com.answer.petsale.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单接口
 *
 * @author answer
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    /**
     * 用户提交预定申请（创建一个待审核的订单）
     */
    @PostMapping("/create")
    @AuthCheck
    public BaseResponse<Long> createOrder(@RequestBody OrderCreateRequest orderCreateRequest, HttpServletRequest request) {
        if (orderCreateRequest == null || orderCreateRequest.getAnimalId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        final User loginUser = userService.getLoginUser(request);
        long orderId = orderService.createOrder(orderCreateRequest, loginUser);
        return ResultUtils.success(orderId);
    }

    /**
     * 管理员批准一个订单申请
     */
    @PostMapping("/approve/{orderId}")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> approveOrderApplication(@PathVariable long orderId) {
        if (orderId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "订单ID无效");
        }
        boolean result = orderService.approveOrder(orderId);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "批准操作失败");
        }
        return ResultUtils.success(true);
    }

    // START: 新增代码 (将此整个方法添加到 approveOrderApplication 方法的后面)
    /**
     * 管理员拒绝一个订单申请
     */
    @PostMapping("/reject")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> rejectOrderApplication(@RequestBody OrderRejectRequest rejectRequest) {
        // 1. 参数校验
        if (rejectRequest == null || rejectRequest.getId() <= 0 || StringUtils.isBlank(rejectRequest.getReason())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不完整");
        }
        // 2. 调用服务层方法
        boolean result = orderService.rejectOrder(rejectRequest.getId(), rejectRequest.getReason());
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "拒绝操作失败");
        }
        // 3. 返回成功响应
        return ResultUtils.success(true);
    }
    // END: 新增代码

    /**
     * 根据 id 获取订单详情
     */
    @GetMapping("/get/vo")
    @AuthCheck
    public BaseResponse<OrderVO> getOrderVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Order order = orderService.getById(id);
        if (order == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        final User loginUser = userService.getLoginUser(request);
        if (!order.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权查看该订单");
        }
        OrderVO orderVO = orderService.getOrderVO(order);
        return ResultUtils.success(orderVO);
    }

    /**
     * 分页获取当前用户的订单列表
     */
    @PostMapping("/my/list/page")
    @AuthCheck
    public BaseResponse<Page<OrderVO>> listMyOrderByPage(@RequestBody OrderQueryRequest orderQueryRequest,
                                                         HttpServletRequest request) {
        final User loginUser = userService.getLoginUser(request);
        Page<Order> orderPage = orderService.page(new Page<>(orderQueryRequest.getCurrent(), orderQueryRequest.getPageSize()),
                orderService.getQueryWrapper(orderQueryRequest).eq("userId", loginUser.getId()));

        return getOrderVOPage(orderPage);
    }

    /**
     * [管理员] 分页获取所有订单列表
     */
    @GetMapping("/admin/list/page")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Page<OrderVO>> listAdminOrderByPage(OrderQueryRequest orderQueryRequest) {
        Page<Order> orderPage = orderService.page(new Page<>(orderQueryRequest.getCurrent(), orderQueryRequest.getPageSize()),
                orderService.getQueryWrapper(orderQueryRequest));

        return getOrderVOPage(orderPage);
    }

    /**
     * 辅助方法：将 Page<Order> 转换为 Page<OrderVO>
     */
    private BaseResponse<Page<OrderVO>> getOrderVOPage(Page<Order> orderPage) {
        List<OrderVO> orderVOList = orderPage.getRecords().stream()
                .map(orderService::getOrderVO)
                .collect(Collectors.toList());

        Page<OrderVO> orderVOPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        orderVOPage.setRecords(orderVOList);

        return ResultUtils.success(orderVOPage);
    }
}